package com.cloud.sso.web;

import com.cloud.sso.common.exception.AppException;
import com.cloud.sso.common.page.AppPageInfo;
import com.cloud.sso.common.result.Result;
import com.cloud.sso.dto.OrgQueryDto;
import com.cloud.sso.dto.OrgSaveDto;
import com.cloud.sso.entity.SysOrg;
import com.cloud.sso.service.OrgService;
import com.cloud.sso.vo.OrgVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 组织处理类
 */
@RestController
@RequestMapping("/api/org")
public class OrgController {

    @Autowired
    private OrgService orgService;

    /**
     * 查询根节点组织 *
     *
     * @return
     */
    @RequestMapping("/root")
    public Result<List<OrgVo>> root() {
        return Result.success(orgService.rootOrg());
    }

    /**
     * 查询直接下级组织 *
     *
     * @param orgId
     * @return
     */
    @RequestMapping("/sub")
    public Result<List> subOrg(@RequestParam String orgId) {
        return Result.success(orgService.subOrg(orgId));
    }

    /**
     * 查询组织详情 *
     *
     * @param id
     * @return
     */
    @RequestMapping("/get")
    public Result<SysOrg> get(@RequestParam String id) {
        return Result.success(orgService.get(id));
    }


    /**
     * 分页查询组织 *
     *
     * @param dto
     * @return
     */
    @RequestMapping("/query")
    public Result<AppPageInfo> queryByPage(@RequestBody OrgQueryDto dto) {
        return Result.success(orgService.queryByPage(dto));
    }

    /**
     * 新增组织 *
     *
     * @param orgSaveDto
     * @param result
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody @Validated OrgSaveDto orgSaveDto, BindingResult result) {
        if (result.hasErrors()) {
            throw new AppException(result.getFieldError().getDefaultMessage());
        }

        orgService.save(orgSaveDto);
        return Result.success(1);
    }

    /**
     * 修改组织 *
     *
     * @param orgSaveDto
     * @param result
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody @Validated OrgSaveDto orgSaveDto, BindingResult result) {
        if (result.hasErrors()) {
            throw new AppException(result.getFieldError().getDefaultMessage());
        }
        orgService.save(orgSaveDto);
        return Result.success(1);
    }

    /**
     * 删除组织
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    public Result delete(@RequestParam String id) {
        orgService.deleteOrg(id);
        return Result.success(1);
    }
}
